<template>
	<div id="warpper" ref="warpper">
		<div class="toolbar">
			<div class="toggle">
				<v-icon v-bind:name="iconName" v-on:click="toggle" />
			</div>
			<div class="title">
				<span>Little Stock</span>
			</div>
			<div class="setting" v-bind:class="{ hidden: !settingButtionIsShow }" v-on:click="settingToggle">
				<v-icon name="cog" />
			</div>
			<div class="clearfix">&nbsp;</div>
		</div>
		<div class="content" v-bind:class="{ 'display-none': !contentIsShow }">
			<div class="stock-list">
				<transition-group name="list" tag="ul">
					<li v-for="stock in stockList" appear v-bind:key="stock.code">
						<span class="list-item">
							{{
								`「${stock.name}」${keepDecimal(stock.price, calcFixedNumber(stock))} ${
									stock.percent >= 0 ? '📈' : '📉'
								} ${keepDecimal(stock.percent * 100, 2)}%`
							}}
						</span>
					</li>
				</transition-group>
			</div>
			<div class="setting-content" v-bind:class="{ 'display-none': !settingContentIsShow }">
				<v-textarea
					placeholder="请输入股票代码"
					rows="10"
					v-bind:defaultValue="this.stockCodes"
					v-on:change="stockListChange"
				></v-textarea>
			</div>
		</div>
	</div>
</template>
<script>
import 'vue-awesome/icons/cog';
import 'vue-awesome/icons/chevron-up';
import 'vue-awesome/icons/chevron-down';
import Icon from 'vue-awesome/components/Icon';
import ListTextArea from './StockWatch/ListTextArea';
import request from 'request';
const baseUrl = 'https://api.money.126.net/data/feed/';
export default {
	name: 'stock-watch',
	components: {
		'v-icon': Icon,
		'v-textarea': ListTextArea,
	},
	data: function () {
		return {
			iconName: 'chevron-up',
			contentIsShow: true,
			updateInterval: 10000,
			settingContentIsShow: false,
			settingButtionIsShow: true,
			stockCodes: [],
			stockList: [],
		};
	},
	methods: {
		keepDecimal: function (num, fixed) {
			var result = parseFloat(num);
			if (isNaN(result)) {
				return '--';
			}
			return result.toFixed(fixed);
		},
		calcFixedNumber: function (item) {
			var high =
				String(item.high).indexOf('.') === -1 ? 0 : String(item.high).length - String(item.high).indexOf('.') - 1;
			var low = String(item.low).indexOf('.') === -1 ? 0 : String(item.low).length - String(item.low).indexOf('.') - 1;
			var open =
				String(item.open).indexOf('.') === -1 ? 0 : String(item.open).length - String(item.open).indexOf('.') - 1;
			var yest =
				String(item.yestclose).indexOf('.') === -1
					? 0
					: String(item.yestclose).length - String(item.yestclose).indexOf('.') - 1;
			var updown =
				String(item.updown).indexOf('.') === -1 ? 0 : String(item.updown).length - String(item.updown).indexOf('.') - 1;
			var max = Math.max(high, low, open, yest, updown);

			if (max === 0) {
				max = 2;
			}

			return max;
		},
		getStockCodes: function (stocks) {
			return stocks.map(code => {
				if (isNaN(code[0])) {
					if (code.toLowerCase().indexOf('us_') > -1) {
						return code.toUpperCase();
					} else if (code.indexOf('hk') > -1) {
						return code;
					} else {
						return code.toLowerCase().replace('sz', '1').replace('sh', '0');
					}
				} else {
					return (code[0] === '6' ? '0' : '1') + code;
				}
			});
		},
		toggle: function (e) {
			this.contentIsShow = !this.contentIsShow;
			var win = this.$electron.remote.getCurrentWindow();
			var size = win.getContentSize();
			if (this.contentIsShow) {
				this.iconName = 'chevron-up';
				this.settingButtionIsShow = true;
				win.setContentSize(size[0], 300);
			} else {
				this.iconName = 'chevron-down';
				this.settingButtionIsShow = false;
				win.setContentSize(size[0], 40);
			}
		},
		settingToggle: function (e) {
			this.settingContentIsShow = !this.settingContentIsShow;
		},
		stockListChange: function (before, after) {
			this.stockCodes = after;
			this.fetchAllData();
			this.saveUserSetting();
		},
		fetchAllData: function () {
			var codes = this.getStockCodes(this.stockCodes);
			var url = `${baseUrl}${codes.join(',')}?callback=a`;
			const net = this.$electron.remote.net;
			var self = this;
			request({ url: url }, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					const result = JSON.parse(body.slice(2, -2));
					let data = [];
					Object.keys(result).map(item => {
						if (!result[item].code) {
							result[item].code = item; //兼容港股美股
						}
						data.push(result[item]);
					});
					for (let index = 0; index < data.length; index++) {
						self.stockList.splice(index, 1);
						self.stockList.splice(index, 1, data[index]);
					}
					// self.stockList. = data;
				}
			});
		},
		saveUserSetting: function () {
			this.$storage.set('stockCodes', this.stockCodes);
		},
	},
	beforeMount() {
		this.stockCodes = this.$userConfig.stockCodes;
	},
	mounted() {
		this.fetchAllData();
		setInterval(this.fetchAllData, this.updateInterval);

		var win = this.$electron.remote.getCurrentWindow();
		var size = win.getContentSize();
		win.setContentSize(size[0], 300);
	},
};
</script>
<style>
#warpper {
	background-color: #fff;
	/* min-height: 1000px; */
}
.toggle {
	width: 20px;
	text-align: center;
	float: left;
	-webkit-app-region: no-drag;
	border: 1px solid #fff;
}
.toggle:hover {
	border: 1px solid black;
}
.title {
	float: left;
	margin-left: 20px;
	cursor: default;
	user-select: none;
}
.setting {
	width: 20px;
	text-align: center;
	float: right;
	-webkit-app-region: no-drag;
	border: 1px solid #fff;
}
.setting:hover {
	border: 1px solid black;
}
.clearfix {
	clear: both;
	visibility: hidden;
	height: 0;
}
.toolbar {
	-webkit-app-region: drag;
	padding: 10px 5px;
}
.display-none {
	display: none;
}
.hidden {
	visibility: hidden;
}
li {
	list-style: none;
	padding: 5px 10px;
}
ul {
	margin: 0;
	padding: 0 0 0 20px;
}
.content {
	position: relative;
	min-height: 250px;
}
.setting-content {
	position: absolute;
	top: 0;
	left: 0;
	width: 230px;
	padding: 0 0 0 20px;
}
.setting-content textarea {
	width: 210px;
	resize: none;
}

.list-item {
	transition: all 1s;
	display: inline-block;
	margin-right: 10px;
}
.list-enter, .list-leave-to
/* .list-complete-leave-active for below version 2.1.8 */ {
	opacity: 0;
	transform: translateY(30px);
}
.list-leave-active {
	position: absolute;
}
</style>